<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('form_csrf')){
	function form_csrf(){
		$CI =& get_instance();
		$html = "<div><input type=\"hidden\" value=\"{$CI->security->get_csrf_hash()}\" name=\"{$CI->security->get_csrf_token_name()}\"></div>";
		return $html;
	}
}
if (!function_exists("getCsrfToken")){
	function getCsrfToken(){
		$CI =& get_instance();
		return $CI->security->get_csrf_hash();
	}
}

if (!function_exists("jsonEncode")){
	function jsonEncode($valueToEncode){
		$CI =& get_instance();
		$CI->load->library('JsonService');
		$json = $CI->jsonservice->encode($valueToEncode);
		return $json;
	}
}

if (!function_exists("jsonDecode")){
	function jsonDecode($encodedValue){
		$CI =& get_instance();
		$CI->load->library('JsonService');
		$json = $CI->jsonservice->decode($encodedValue);
		return $json;
	}
}

if (!function_exists("setting")){
	function setting ($name) {
		$CI =& get_instance();
		return $CI->config->item($name);
	}
}

if (!function_exists("__")){
	function __(){
		$CI =& get_instance();
		$args = func_get_args();
		return $CI->lang->translate($args);
	}
}

if (!function_exists("clean_entities")){
	function clean_entities($fragment)
	{
		$translite_simbols = array ('#(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)#', '#(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)#',  '#(ì|í|ị|ỉ|ĩ)#', '#(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)#',  '#(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)#', '#(ỳ|ý|ỵ|ỷ|ỹ)#', '#(đ)#',  '#(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)#', '#(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)#',  '#(Ì|Í|Ị|Ỉ|Ĩ)#', '#(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)#',  '#(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)#', '#(Ỳ|Ý|Ỵ|Ỷ|Ỹ)#', '#(Đ)#',  "/[^a-zA-Z0-9\-\_]/", '#quot#', ) ; 
		$replace = array ( 'a', 'e', 'i', 'o', 'u',  'y', 'd', 'A', 'E', 'I', 'O', 'U', 'Y', 'D', '-', '', ) ;
		$fragment =  preg_replace($translite_simbols, $replace, trim($fragment)); 
		$fragment = preg_replace('/(-)+/', '-', $fragment);
		return $fragment;
	}
}

if (!function_exists("alias_url")){
	function alias_url($fragment)
	{
		return strtolower(clean_entities($fragment));
	}
}



if(!function_exists("is_dir_writeable")){
	function is_dir_writeable($dir)
	{
	    if (is_dir($dir) && is_writable($dir)) {
	        if (stripos(PHP_OS, 'win') === 0) {
	            $dir    = ltrim($dir, DIRECTORY_SEPARATOR);
	            $file   = $dir . DIRECTORY_SEPARATOR . uniqid(mt_rand()).'.tmp';
	            $exist  = file_exists($file);
	            $fp     = @fopen($file, 'a');
	            if ($fp === false) {
	                return false;
	            }
	            fclose($fp);
	            if (!$exist) {
	                unlink($file);
	            }
	        }
	        return true;
	    }
	    return false;
	}
}

if ( !function_exists('sys_get_temp_dir') ) {
    // Based on http://www.phpit.net/
    // article/creating-zip-tar-archives-dynamically-php/2/
    function sys_get_temp_dir()
    {
        // Try to get from environment variable
        if ( !empty($_ENV['TMP']) ) {
            return realpath( $_ENV['TMP'] );
        } else if ( !empty($_ENV['TMPDIR']) ) {
            return realpath( $_ENV['TMPDIR'] );
        } else if ( !empty($_ENV['TEMP']) ) {
            return realpath( $_ENV['TEMP'] );
        } else {
            // Try to use system's temporary directory
            // as random name shouldn't exist
            $temp_file = tempnam( md5(uniqid(rand(), TRUE)), '' );
            if ( $temp_file ) {
                $temp_dir = realpath( dirname($temp_file) );
                unlink( $temp_file );
                return $temp_dir;
            } else {
                return FALSE;
            }
        }
    }
}
/**
 * Tree Menu Grid data category
 */
if (!function_exists("treerecurse")){
	function treerecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 )
	{
		if (@$children[$id] && $level <= $maxlevel)
		{
			foreach ($children[$id] as $v)
			{
				$id = $v['id'];

				if ( $type ) {
					$pre 	= '<sup>|_</sup>&nbsp;';
					$spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
				} else {
					$pre 	= '- ';
					$spacer = '&nbsp;&nbsp;';
				}

				if ( $v['parent_id'] == 0 ) {
					$txt 	= $v['name'];
				} else {
					$txt 	= $pre . $v['name'];
				}
				$pt = $v['parent_id'];
				$list[$id] = $v;
				$list[$id]['treename'] = "$indent$txt";
				$list[$id]['children'] = count( @$children[$id] );
				$list = treerecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
			}
		}
		return $list;
	}
}

if (!function_exists("lottrery_time_now")){
	function lottrery_time_now(){
		return fdate('now','%H%M');
	}
}
if (!function_exists("get_client_ip")){
	function get_client_ip($checkproxy = true){
		if ($checkproxy && isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != null) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else if ($checkproxy && isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != null) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
	}
}
if (!function_exists("get_curl_data")){
	function get_curl_data($url){
		$data = null;

		if (ini_get('allow_url_fopen') && function_exists('file_get_contents')) {
			$data = file_get_contents($url);
		} else {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$data = curl_exec($ch);
		}
		return $data;
	}
}
if (!function_exists("is_image")){
	/**
	 * Checks if a URL is an image
	 *
	 * @param string
	 * @return URL
	 */
	function is_image( $url )
	{
		$result = preg_match( '#(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$#i', $url );
		return $result;
	}
}

	
if (!function_exists("is_flash")){
	/**
	 * Checks if a URL is a Flash file
	 *
	 * @param string
	 * @return URL
	 */
	function is_flash( $url )
	{
		$result = preg_match( '#\.swf$#i', $url );
		return $result;
	}
}